<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>守护进程 - lclei blog</title>
  <meta name="renderer" content="webkit" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

<meta name="theme-color" content="#f8f5ec" />
<meta name="msapplication-navbutton-color" content="#f8f5ec">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="#f8f5ec">


<meta name="author" content="lclei" /><meta name="description" content="守护进程  生存期长，常常在系统引导装入时启动，仅在系统关闭时终止 没有控制终端  如何编写  umask(0) 调用fork，使父进程exit setsid创建一个新会话 工作目录改为根目录 关闭不需要的文件描述符 关闭标准输入输出 " /><meta name="keywords" content="lclei, blog, code" />






<meta name="generator" content="Hugo 0.68.3 with theme even" />


<link rel="canonical" href="http://localhost:1313/post/daemon/" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">



<link href="/sass/main.min.2e81bbed97b8b282c1aeb57488cc71c8d8c8ec559f3931531bd396bf31e0d4dd.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.css" integrity="sha256-7TyXnr2YU040zfSP+rEcz29ggW4j56/ujTPwjMzyqFY=" crossorigin="anonymous">


<meta property="og:title" content="守护进程" />
<meta property="og:description" content="守护进程

生存期长，常常在系统引导装入时启动，仅在系统关闭时终止
没有控制终端

如何编写

umask(0)
调用fork，使父进程exit
setsid创建一个新会话
工作目录改为根目录
关闭不需要的文件描述符
关闭标准输入输出
" />
<meta property="og:type" content="article" />
<meta property="og:url" content="http://localhost:1313/post/daemon/" />
<meta property="article:published_time" content="2019-12-09T00:00:00+00:00" />
<meta property="article:modified_time" content="2019-12-09T00:00:00+00:00" />
<meta itemprop="name" content="守护进程">
<meta itemprop="description" content="守护进程

生存期长，常常在系统引导装入时启动，仅在系统关闭时终止
没有控制终端

如何编写

umask(0)
调用fork，使父进程exit
setsid创建一个新会话
工作目录改为根目录
关闭不需要的文件描述符
关闭标准输入输出
">
<meta itemprop="datePublished" content="2019-12-09T00:00:00&#43;00:00" />
<meta itemprop="dateModified" content="2019-12-09T00:00:00&#43;00:00" />
<meta itemprop="wordCount" content="539">



<meta itemprop="keywords" content="linux," /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="守护进程"/>
<meta name="twitter:description" content="守护进程

生存期长，常常在系统引导装入时启动，仅在系统关闭时终止
没有控制终端

如何编写

umask(0)
调用fork，使父进程exit
setsid创建一个新会话
工作目录改为根目录
关闭不需要的文件描述符
关闭标准输入输出
"/>

<!--[if lte IE 9]>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
<![endif]-->

<!--[if lt IE 9]>
  <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
<![endif]-->

</head>
<body>
  <div id="mobile-navbar" class="mobile-navbar">
  <div class="mobile-header-logo">
    <a href="/" class="logo">lclei</a>
  </div>
  <div class="mobile-navbar-icon">
    <span></span>
    <span></span>
    <span></span>
  </div>
</div>
<nav id="mobile-menu" class="mobile-menu slideout-menu">
  <ul class="mobile-menu-list">
    <a href="/">
        <li class="mobile-menu-item">Home</li>
      </a><a href="/post/">
        <li class="mobile-menu-item">Archives</li>
      </a><a href="/tags/">
        <li class="mobile-menu-item">Tags</li>
      </a><a href="/categories/">
        <li class="mobile-menu-item">Categories</li>
      </a><a href="/about/">
        <li class="mobile-menu-item">About</li>
      </a>
  </ul>

  


</nav>

  <div class="container" id="mobile-panel">
    <header id="header" class="header">
        <div class="logo-wrapper">
  <a href="/" class="logo">lclei</a>
</div>





<nav class="site-navbar">
  <ul id="menu" class="menu">
    <li class="menu-item">
        <a class="menu-item-link" href="/">Home</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/post/">Archives</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/tags/">Tags</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/categories/">Categories</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/about/">About</a>
      </li>
  </ul>
</nav>

    </header>

    <main id="main" class="main">
      <div class="content-wrapper">
        <div id="content" class="content">
          <article class="post">
    
    <header class="post-header">
      <h1 class="post-title">守护进程</h1>

      <div class="post-meta">
        <span class="post-time"> 2019-12-09 </span>
        
        
      </div>
    </header>

    <div class="post-toc" id="post-toc">
  <h2 class="post-toc-title">Contents</h2>
  <div class="post-toc-content always-active">
    <nav id="TableOfContents">
  <ul>
    <li><a href="#守护进程">守护进程</a>
      <ul>
        <li><a href="#如何编写">如何编写</a></li>
      </ul>
    </li>
  </ul>
</nav>
  </div>
</div>
    <div class="post-content">
      <h1 id="守护进程">守护进程</h1>
<ul>
<li>生存期长，常常在系统引导装入时启动，仅在系统关闭时终止</li>
<li>没有控制终端</li>
</ul>
<h2 id="如何编写">如何编写</h2>
<ol>
<li>umask(0)</li>
<li>调用fork，使父进程exit</li>
<li>setsid创建一个新会话</li>
<li>工作目录改为根目录</li>
<li>关闭不需要的文件描述符</li>
<li>关闭标准输入输出</li>
</ol>
<p>实例</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span><span class="lnt">34
</span><span class="lnt">35
</span><span class="lnt">36
</span><span class="lnt">37
</span><span class="lnt">38
</span><span class="lnt">39
</span><span class="lnt">40
</span><span class="lnt">41
</span><span class="lnt">42
</span><span class="lnt">43
</span><span class="lnt">44
</span><span class="lnt">45
</span><span class="lnt">46
</span><span class="lnt">47
</span><span class="lnt">48
</span><span class="lnt">49
</span><span class="lnt">50
</span><span class="lnt">51
</span><span class="lnt">52
</span><span class="lnt">53
</span><span class="lnt">54
</span><span class="lnt">55
</span><span class="lnt">56
</span><span class="lnt">57
</span><span class="lnt">58
</span><span class="lnt">59
</span><span class="lnt">60
</span><span class="lnt">61
</span><span class="lnt">62
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-c" data-lang="c"><span class="cp">#include</span> <span class="cpf">&#34;apue.h&#34;</span><span class="cp">
</span><span class="cp">#include</span> <span class="cpf">&lt;syslog.h&gt;</span><span class="cp">
</span><span class="cp">#include</span> <span class="cpf">&lt;fcntl.h&gt;</span><span class="cp">
</span><span class="cp">#include</span> <span class="cpf">&lt;sys/resource.h&gt;</span><span class="cp">
</span><span class="cp"></span>
<span class="kt">void</span> <span class="nf">deamonize</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">cmd</span><span class="p">){</span>
  <span class="kt">int</span> <span class="n">i</span><span class="p">,</span> <span class="n">fd0</span><span class="p">,</span> <span class="n">fd1</span><span class="p">,</span> <span class="n">fd2</span><span class="p">;</span>
  <span class="n">pid_t</span> <span class="n">pid</span><span class="p">;</span>
  <span class="k">struct</span> <span class="n">rlimit</span> <span class="n">rl</span><span class="p">;</span>
  <span class="k">struct</span>  <span class="n">sigaction</span> <span class="n">sa</span><span class="p">;</span>

  <span class="c1">// Clear file creation umask
</span><span class="c1"></span>  <span class="n">umask</span><span class="p">(</span><span class="mi">0</span><span class="p">);</span>

  <span class="c1">// Get maximum number of file descriptors
</span><span class="c1"></span>  <span class="k">if</span> <span class="p">(</span><span class="n">getrlimit</span><span class="p">(</span><span class="n">RLIMIT_NOFILE</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">rl</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span>
    <span class="n">err_quit</span><span class="p">(</span><span class="s">&#34;%s: can&#39;t get file limt&#34;</span><span class="p">,</span> <span class="n">cmd</span><span class="p">);</span>

  <span class="c1">// Become a session leader to lose controlling TTY
</span><span class="c1"></span>  <span class="k">if</span><span class="p">(</span> <span class="p">(</span><span class="n">pid</span><span class="o">=</span><span class="n">fork</span><span class="p">())</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span>
    <span class="n">err_quit</span><span class="p">(</span><span class="s">&#34;%s: can&#39;t get file limit&#34;</span><span class="p">,</span> <span class="n">cmd</span><span class="p">);</span>
  <span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="n">pid</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">)</span> <span class="c1">// Parent
</span><span class="c1"></span>    <span class="n">exit</span><span class="p">(</span><span class="mi">0</span><span class="p">);</span>
  <span class="n">setsid</span><span class="p">();</span>

  <span class="c1">// Ensure future opens won&#39;t allocate controlling TTYs
</span><span class="c1"></span>  <span class="n">sa</span><span class="p">.</span><span class="n">sa_handler</span> <span class="o">=</span> <span class="n">SIG_IGN</span><span class="p">;</span>
  <span class="n">sigemptyset</span><span class="p">(</span><span class="o">&amp;</span><span class="n">sa</span><span class="p">.</span><span class="n">sa_mask</span><span class="p">);</span>
  <span class="n">sa</span><span class="p">.</span><span class="n">sa_flags</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">sigaction</span><span class="p">(</span><span class="n">SIGHUP</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">sa</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span>
    <span class="n">err_quit</span><span class="p">(</span><span class="s">&#34;%s: can&#39;t ignore SIGHUP&#34;</span><span class="p">,</span> <span class="n">cmd</span><span class="p">);</span>
  <span class="k">if</span> <span class="p">((</span><span class="n">pid</span> <span class="o">=</span> <span class="n">fork</span><span class="p">())</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span>
    <span class="n">err_quit</span><span class="p">(</span><span class="s">&#34;%s: can&#39;t fork&#34;</span><span class="p">,</span> <span class="n">cmd</span><span class="p">);</span>
  <span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="n">pid</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">)</span>
    <span class="n">exit</span><span class="p">(</span><span class="mi">0</span><span class="p">);</span>

  <span class="c1">// Change the cuurent working directory to the root so
</span><span class="c1"></span>  <span class="c1">// we won&#39;t prevent file systems from being unmounted.
</span><span class="c1"></span>
  <span class="k">if</span> <span class="p">(</span><span class="n">chdir</span><span class="p">(</span><span class="s">&#34;/&#34;</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span>
    <span class="n">err_quit</span><span class="p">(</span><span class="s">&#34;%s: can&#39;t change directory to /&#34;</span><span class="p">,</span> <span class="n">cmd</span><span class="p">);</span>

  <span class="c1">// Close all the file descriptors
</span><span class="c1"></span>  <span class="k">if</span><span class="p">(</span><span class="n">rl</span><span class="p">.</span><span class="n">rlim_max</span> <span class="o">==</span> <span class="n">RLIM_INFINITY</span><span class="p">)</span>
    <span class="n">rl</span><span class="p">.</span><span class="n">rlim_max</span> <span class="o">=</span> <span class="mi">1024</span><span class="p">;</span>
  <span class="k">for</span><span class="p">(</span><span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span><span class="n">i</span> <span class="o">&lt;</span><span class="n">rl</span><span class="p">.</span><span class="n">lim_max</span><span class="p">;</span><span class="n">i</span><span class="o">++</span><span class="p">)</span>
    <span class="n">close</span><span class="p">(</span><span class="n">i</span><span class="p">);</span>

  <span class="c1">// Attach file descriptors 0, 1, 2 to /dev/ull
</span><span class="c1"></span>  <span class="n">fd0</span> <span class="o">=</span> <span class="n">open</span><span class="p">(</span><span class="s">&#34;/dev/null&#34;</span><span class="p">,</span> <span class="n">O_RDWR</span><span class="p">);</span>
  <span class="n">fd1</span> <span class="o">=</span> <span class="n">dup</span><span class="p">(</span><span class="mi">0</span><span class="p">);</span>
  <span class="n">fd2</span> <span class="o">=</span> <span class="n">dup</span><span class="p">(</span><span class="mi">0</span><span class="p">);</span>

  <span class="c1">// Initiallize the log file
</span><span class="c1"></span>  <span class="n">openlog</span><span class="p">(</span><span class="n">cmd</span><span class="p">,</span> <span class="n">LOG_CONS</span><span class="p">,</span> <span class="n">LOG_DAEMON</span><span class="p">);</span>
  <span class="k">if</span><span class="p">(</span><span class="n">fd0</span><span class="o">!=</span><span class="mi">0</span> <span class="o">||</span> <span class="n">fd1</span> <span class="o">!=</span> <span class="mi">1</span> <span class="o">||</span> <span class="n">fd2</span> <span class="o">!=</span> <span class="mi">2</span><span class="p">){</span>
    <span class="n">syslog</span><span class="p">(</span><span class="n">LOG_ERR</span><span class="p">,</span> <span class="s">&#34;unexpected file descriptors %d %d %d&#34;</span><span class="p">,</span> <span class="n">fd0</span><span class="p">,</span> <span class="n">fd1</span><span class="p">,</span> <span class="n">fd2</span><span class="p">);</span>
    <span class="n">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span>
  <span class="p">}</span>


<span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><p>下面使用daemonize将main函数变为守护进程</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">void daemonize(const char *cmd);
int main(int argc, char **argv){
  daemonize(&#34;main&#34;);
  sleep(110);
}
</code></pre></td></tr></table>
</div>
</div><p>查看执行结果</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">lcl@FX50JK:~/Documents/hub/learning-record/linux/daemon$ ps -efj | grep ./main
lcl      23738  1542 23737 23737  0 17:13 ?        00:00:00 ./main
lcl      23744  6959 23743  6959  0 17:14 pts/1    00:00:00 grep --color=auto ./main

</code></pre></td></tr></table>
</div>
</div><p>与一个正常非守护进程main1对比</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">lcl@FX50JK:~/Documents/hub/learning-record/linux/daemon$ ps -efj | grep ./main
UID        PID  PPID  PGID   SID  C STIME TTY          TIME CMD
lcl      24079  1542 24078 24078  0 18:17 ?        00:00:00 ./main
lcl      24089  2166 24089  2166  0 18:18 pts/0    00:00:00 ./main1
</code></pre></td></tr></table>
</div>
</div><p>可见守护进程没有绑定终端，在孤儿进程组，不是会话首进程</p>
    </div>

    <div class="post-copyright">
  <p class="copyright-item">
    <span class="item-title">Author</span>
    <span class="item-content">lclei</span>
  </p>
  <p class="copyright-item">
    <span class="item-title">LastMod</span>
    <span class="item-content">
        2019-12-09
        
    </span>
  </p>
  
  
</div>
<footer class="post-footer">
      <div class="post-tags">
          <a href="/tags/linux/">linux</a>
          </div>
      <nav class="post-nav">
        <a class="prev" href="/post/polymorphism/">
            <i class="iconfont icon-left"></i>
            <span class="prev-text nav-default">多态 polymorphism</span>
            <span class="prev-text nav-mobile">Prev</span>
          </a>
        <a class="next" href="/post/inserter/">
            <span class="next-text nav-default">插入迭代器</span>
            <span class="next-text nav-mobile">Next</span>
            <i class="iconfont icon-right"></i>
          </a>
      </nav>
    </footer>
  </article>
        </div>
        

  

  

      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="social-links">
      <a href="mailto:lclei@mail.ustc.edu.cn" class="iconfont icon-email" title="email"></a>
      <a href="https://gitee.com/lclei" class="iconfont icon-gitee" title="gitee"></a>
      <a href="https://gitee.com/lclei" class="iconfont icon-github" title="github"></a>
  <a href="http://localhost:1313/index.xml" type="application/rss+xml" class="iconfont icon-rss" title="rss"></a>
</div>

<div class="copyright">
  <span class="power-by">
    Powered by <a class="hexo-link" href="https://gohugo.io">Hugo</a>
  </span>
  <span class="division">|</span>
  <span class="theme-info">
    Theme - 
    <a class="theme-link" href="https://github.com/olOwOlo/hugo-theme-even">Even</a>
  </span>

  

  <span class="copyright-year">
    &copy; 
    2018 - 
    2022<span class="heart"><i class="iconfont icon-heart"></i></span><span>lclei</span>
  </span>
</div>

    </footer>

    <div class="back-to-top" id="back-to-top">
      <i class="iconfont icon-up"></i>
    </div>
  </div>
  
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/slideout@1.0.1/dist/slideout.min.js" integrity="sha256-t+zJ/g8/KXIJMjSVQdnibt4dlaDxc9zXr/9oNPeWqdg=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.js" integrity="sha256-XVLffZaxoWfGUEbdzuLi7pwaUJv1cecsQJQqGLe7axY=" crossorigin="anonymous"></script>



<script type="text/javascript" src="/js/main.min.c12618f9a600c40bd024996677e951e64d3487006775aeb22e200c990006c5c7.js"></script>








</body>
</html>
